﻿using CallCenter.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;

namespace CallCenter.Security
{
    public interface IFormsAuthentication
    {
        void SignIn(string userName, int id, bool createPersistentCookie,string RoleName);
        void SignOut();
    }
    public class FormsAuthenticationService : IFormsAuthentication
    {
        private readonly DataManager _db = null;

        public FormsAuthenticationService(DataManager db)
        {
            this._db = db;
        }
        public string SignedInUsername
        {
            get { return HttpContext.Current.User.Identity.Name; }
        }

        public DateTime? SignedInTimestampUtc
        {
            get
            {
                var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
                if (cookie != null)
                {
                    var ticket = FormsAuthentication.Decrypt(cookie.Value);
                    return ticket.IssueDate.ToUniversalTime();
                }
                else
                {
                    return null;
                }
            }
        }

        public void SignIn(string userName, int userId, bool createPersistentCookie,string RoleName)
        {
            FormsAuthentication.SignOut();

            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);

            
            HttpContext.Current.Session["SessionHelper"] = userName;

            HttpContext.Current.Session["SessionUserId"] = userId;
            HttpContext.Current.Session["UserRole"] = RoleName.ToLower();


            // Check username and assign role
            //if (!string.IsNullOrEmpty(userName) && userName.Equals("dan", StringComparison.InvariantCultureIgnoreCase))
            //    HttpContext.Current.Session["UserRole"] = "admin";
            //else
            //    HttpContext.Current.Session["UserRole"] = "user";
        }

        public void SignOut()
        {
            FormsAuthentication.SignOut();
            HttpContext.Current.Session.Abandon();
        }
    }
}
